// pages/video/video.js
const app = getApp()
let interstitialAd = null //插屏广告
let videoAd = null //视频激励广告
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		dataC: true,
		hisShow: true, //头部提示是否显示
		recommend: [],
		vid: 0,
		listHis: [],
		urlId: null, //当前视频id
		jIndex: 0, //集数被点击的索引
		videoTime: 0, //当前视频播放进度
		ijia: 0, //秒
		vTitle: "爱宅域影视",
		url: null,
		videoUrl: [], //视频全部源
		videoY: [], //传一条视频源======显示
		videoId: [],
		videoFrom: [], //视频播放源名字
		src: "",
		info: {
			title: "loading...",
			Id: null,
			type_id: null,
			score: "null",
			j: "",
			year: "",
			address: "",
			remarks: "",
			actor: "",
			img: "",

			jj: "",
			videoSum: null

		},
		isF: true,
		isV: true,
		collect: false,
		dataC: null,
		click: false, //是否显示弹窗内容
		// option: false, //显示弹窗或关闭弹窗的操作动画
		msgList: [], //视频下方文文字提示

		index: 0, //视频播放源
		sudu: 1, //视频播放速度
		showModal: false, //按钮的显示或隐藏
		spE: "contain", //视频适应状态
		sptext: "全屏" //视频适应状态文字
	},
	/* 
	 获取指定内容的视频
	 */
	getVideo(id) {

		let that = this;

		//赋值id给分享调用
		that.setData({
			Id: id
		})
		wx.request({
			url: app.globalData.Url + "public/?service=App.Mov.GetOnlineMvById",
			data: {
				vodid: id
			},
			success: (res) => {
				console.log(res);
				let ssn = res.data.Data;
				console.log("长度:")
				console.log(ssn.length)
				//判断视频 
				if (ssn.length === 1) {
					console.log("视频正常")
				} else {
					//console.log("空")
					wx.showModal({
						title: "提示",
						content: "视频不存在或已被下架,请联系管理员",
						success: function(res) {
							if (res.confirm) {
								console.log("确定");
								wx.navigateBack({
									delta: 1
								});
							} else {
								wx.navigateBack({
									delta: 1
								});
								console.log("取消")
							}
						}
					})
				}
				//判断视频



				//赋值
				let data = res.data.Data["0"];
				that.setData({
					title: data.vod_name,
					score: data.vod_score,
					type_id: data.type_id, //类型id
					year: data.vod_year,
					address: data.vod_area,
					remarks: data.vod_remarks,
					actor: data.vod_actor,
					img: data.vod_pic,
					jj: data.vod_content,
					urlId: data.vod_id //当前视频id
				})
				//设置视频标题
				let title = res.data.Data["0"].vod_name;
				this.setData({
					vTitle: title
				})
				wx.setNavigationBarTitle({ //页面标题
					title: title
				})
				let Arr = new Array(); //播放源分割
				// console.log(res.data.Data["0"].vod_play_from);
				let playFrom = res.data.Data["0"].vod_play_from;
				let play_from = playFrom.split("$$$"); //播放源
				//分割播放器放到数组
				let fromV = new Array();
				fromV = play_from
				console.log(fromV)
				//播放源
				that.setData({
					videoSum: fromV
				});
				// console.log(play_from)
				let playUrl = res.data.Data["0"].vod_play_url;
				let play_url = playUrl.split("$$$"); //播放地址

				var arr = new Array();
				// var yy=new Array();
				for (let i = 0; i < play_from.length; i++) { //有几个播放器



					console.log("第" + (i + 1) + "层");
					// arr[i]=b[i];
					let x = play_url[i].split("#"); //把播放地址和标题分分割为一个数组
					// console.log(x);
					Arr[i] = x; //赋给arr的第几个
					arr[i] = Arr[i];
					// console.log(Arr[i]);
					for (let j = 0; j < Arr[i].length; j++) {
						// Arr[i][j].split("$");
						arr[i][j] = Arr[i][j].split("$"); //把播放地址和标题分开
						// console.log(Arr[i][j].split("$"))
						// console.log(Arr);
					}

				}
				console.log("循环完成")
				console.log(arr); //

				//先添加记录
				//that.setHis(0,0);

				let hisss = wx.getStorageSync("his");
				//console.log("或最新",hisss); 
				if (hisss.length != 0) { //判断有没有记录缓存

					that.setData({
						// //传递播放源第一条视频url 
						src: arr[0][0][1],
						// //传递集bt
						j: arr[0][0][0],
					})

					for (var i = 0; i <= hisss.length - 1; i++) {
						if (that.data.urlId == hisss[i]["0"].id) {
							//判断如果和当前id相同的话
							console.log("当前历史id", hisss[i]["0"].id);
							console.log("当前url id", that.data.urlId);
							var jindex = hisss[i]["0"]["jindex"];
							var time = hisss[i]["0"]["time"];
							if (hisss[i]["0"].id != null) {
								//判断是那个视频
								console.log("读取进度", time)
								that.setData({
									videoTime: time,
									jIndex: jindex,
									// //传递播放源视频url
									src: arr[0][jindex][1],
									// //传递集bt
									j: arr[0][jindex][0],
								});
								wx.showToast({
									title: '已为您转跳到上次观看进度',
									icon: 'none',
									duration: 2000 //持续的时间
								})
							} else {
								that.setData({
									// //传递播放源第一条视频url 
									src: arr[0][0][1],
									// //传递集bt
									j: arr[0][0][0],
								})
							}
						}
					}
				} else {
					//第一次
					that.setData({
						// //传递播放源第一条视频url 
						src: arr[0][0][1],
						// //传递集bt
						j: arr[0][0][0],
					})
				}

				////////////

				that.setData({
					videoId: res.data.Data,
					//循环arr
					videoUrl: arr, //播放源
					videoY: arr[0], //获取一个播放源[index] ======显示
				})
				that.ifCollect(); //判断收藏
				// 执行推荐
				that.getTj();


			}
		})
	},
	//绑定选择器
	change: function(e) {
		console.log("选择改变，携带值为", e.detail.value)
		this.setData({
			index: e.detail.value,
			videoY: this.data.videoUrl[
				e.detail.value]
		})
		console.log(this.data.videoUrl[e.detail.value])

	},
	//
	getDataC() {
		let that = this;
		wx.request({
			url: app.globalData.Url + "public/?service=App.DataControl.User",
			data: {
				dataC: 1
			},
			success: (src) => {

				if (src.data.Code === 200) {
					that.setData({
						dataC: src.data.Data.content
					})
				} else {
					console.log("错误");
				}
			}
		})
	},


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.getVideo(options.id);
		this.getDataC();
		this.getVideoId();
		this.videoCtx = wx.createVideoContext('myVideo');
		this.tisVideo(); //判断头部提示
		this.ad(); //广告


		//视频加载
		// this.videoCtx=wx.createAudioContext('myVideo');
		//缓冲提醒
		wx.showToast({
			title: '加载中',
			icon: 'loading',
			duration: 400
		})

		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline'],
		}) //分享
	},
	// 视频播放错误
	videoError() {
		wx.showModal({
			title: "提示",
			content: "视频播放出错,请切换播放线路试试",
			success: function(res) {
				if (res.confirm) {
					console.log("确定");
					// wx.navigateBack({
					// 	delta: 1
					// });
				} else {
					// wx.navigateBack({
					// 	delta: 1
					// });
					console.log("取消")
				}
			}
		})
	},
	// 图片预览
	pic(){
		var urrl=[];
		urrl=this.data.img;
		    wx.previewImage({
		      current: urrl, // 当前显示图片的http链接
		      urls: [urrl] // =============重点重点=============
		    })
	},
	/* 
	 点击关注
	 */
	contact() {
		this.setData({
			showModal: true
		});

	},
	// 弹窗ok
	okok: function() {
		this.setData({
			showModal: false
		})
	},
	/* 
	 点击加速
	 */
	sudu() {
		var num = Number(this.data.sudu);
		switch (num) {
			case 0.5:
				// this.data.sudu=num+0.5;
				this.setData({
					sudu: num + 0.5
				})
				this.videoCtx.playbackRate(this.data.sudu);
				console.log(this.data.sudu)
				break;
			case 1:
				this.setData({
					sudu: num + 0.25
				})
				this.videoCtx.playbackRate(this.data.sudu);
				console.log(this.data.sudu)
				break;

			case 1.25:
				this.setData({
					sudu: num + 0.25
				})
				this.videoCtx.playbackRate(this.data.sudu);
				console.log(this.data.sudu)
				break;

			case 1.5:
				this.setData({
					sudu: num + 0.5
				})
				this.videoCtx.playbackRate(this.data.sudu);
				console.log(this.data.sudu)
				break;

			case 2:
				this.setData({
					sudu: 0.5
				})
				this.videoCtx.playbackRate(this.data.sudu);
				console.log(this.data.sudu)
				break;
		}
	},
	/*
	 点击下载
	 */
	dowUrl() {
		wx.setClipboardData({
			data: this.data.src,
			success: (res) => {
				wx.showToast({
					title: "播放地址复制成功,请用手机浏览器打开",
					icon: "none",
					duration: 2000
				});
			}
		});

		// 用户触发广告后，显示激励视频广告
		if (this.videoAd) {
			this.videoAd.show().catch(() => {
				// 失败重试
				this.videoAd.load()
					.then(() => this.videoAd.show())
					.catch(err => {
						console.log('激励视频 广告显示失败')
					})
			})
		}

	},
	// 屏幕适应 全fill
	spE() {
		if (this.data.spE == "contain") {
			this.setData({
				spE: "fill",
				sptext: "自适应"
			})
		} else {
			this.setData({
				spE: "contain",
				sptext: "全屏"
			})
		}
	},
	/*
	 收藏
	 */
	collect() {
		let that = this;
		if (this.data.collect!=true) {
			console.log("没收藏");
			// 缓存多条数据
			let co = [{
				"id": this.data.urlId,
				"name": this.data.title,
				"pic": this.data.img,
				"remarks": this.data.remarks,
			}]; //新一条的
			let coll = wx.getStorageSync("collect") || [];
			coll.unshift(co);
			wx.setStorageSync("collect", coll);
			
			wx.showToast({
				title: "已收藏",
				icon: 'none',
				duration: 1500 //持续的时间
			});
			that.setData({
				collect: true
			})
		} else {
			let col = Array();
			col = wx.getStorageSync("collect");
			for(var i in col){
				if(this.data.urlId==col[i]["0"].id){
					col.splice(i, 1) //删除
				}
			}
			wx.setStorageSync("collect", col); //赋值替换全部
			wx.showToast({
				title: "已移出收藏",
				icon: 'none',
				duration: 1500 //持续的时间
			});
			that.setData({
				collect: false
			})
		}

	},
	ifCollect() {
		var col = Array();
		col = wx.getStorageSync("collect");
		if (col.length == 0) {
			this.setData({
				collcet: false
			})
			console.log("收藏空间不存在")
		} else {

			for (let i in col) {
				console.log(i,this.data.collect)
				if (this.data.urlId == col[i]["0"].id) {
					this.setData({
						collect: true
					})
				}
			}
		}

	},
	/* 
	简介展开
	 */
	zk: function() {
		this.setData({
			isF: !this.data.isF
		})
	},
	/* 
	 视频展开
	 */
	spzk: function() {
		this.setData({
			isV: !this.data.isV
		})
	},
	/* 
	 视频逻辑处理
	 */
	getVideoId() {
		var a = this.videoId;

	},
	/* 
	 根据类型推荐
	 */
	getTj() {
		let that = this;
		wx.request({
			url: app.globalData.Url + "public/?service=App.Mov.GetRecommend",
			data: {
				type: that.data.type_id,
				limit: 9,
				page: 1
			},
			success: (res) => {
				console.log("推荐", res)
				if (res.data.Code == 200) {
					that.setData({
						recommend: res.data.Data
					})
				} else {

				}
			}

		})
	},


	/* 
	 视频控制
	 */
	playVideo: function(e) {
		this.videoCtx.stop();
		//停止当前视频
		console.log(e);
		//更新播放地址
		this.setData({
			src: e.currentTarget.dataset.url,
			j: e.currentTarget.dataset.j,
			jIndex: e.currentTarget.dataset.index
		});
		//播放新的视频
		this.videoCtx.play();
		//提示
		wx.showToast({
			title: "视频正在切换，请稍等",
			icon: "none",
			duration: 1500
		});
		//
		let his = wx.getStorageSync("his"); //历史
		this.data.jIndex = e.currentTarget.dataset.index;
		this.data.ijia = 0;
		this.setData({
			videoTime: 0,

		});

		// 在适合的场景显示插屏广告
		if (this.interstitialAd) {
			this.interstitialAd.show().catch((err) => {
				console.error(err)
			})

		}

	},

	/* 视频中途加载 */
	vError: function(e) {
		console.log(e);
		wx.showToast({
			title: "加载中...",
			icon: "none",
			duration: 1500
		});
	},
	/* 视频缓冲事件 */
	load: function(e) {
		wx.showToast({
			title: "视频入载中",
			icon: "none",
			duration: 1500
		});
	},
	//获取视频播放进度
	getTime(e) {
		// console.log(e.detail.currentTime);
		var time = Number(e.detail.currentTime);

		this.data.videoTime = time;
		var i = time;
		if (i > this.data.ijia + 5) {
			console.log(time);
			this.data.ijia = time; //实现五秒执行一次

			this.setHis(this.data.jIndex, time);
		}
	},
	/* 
	 设置本地缓存记录
	 */
	setHis(j, time) {
		////////////////////////////////
		console.log(j);
		//添加历史记录
		let His = [{
			"id": this.data.urlId,
			"name": this.data.title,
			"pic": this.data.img,
			"remarks": this.data.remarks,
			"time": time, //播放进度时间
			"jindex": j, //按钮索引
		}]; //新一条的
		console.log("历史获取id", this.data.title)
		var his = Array();
		his = wx.getStorageSync("his"); //全部的
		// that.setData({
		// 	listHis:his
		// })
		console.log("添加", his);

		if (his.length <= 0) {
			// 缓存多条数据
			let arrH = wx.getStorageSync("his") || [];
			arrH.unshift(His);
			wx.setStorageSync("his", arrH);

		} else {



			for (let i = 0, j = 1; i <= his.length - 1; i++, j++) { //循环相同内容
				if (this.data.urlId == his[i]["0"].id) { //判断旧的观看记录是否存在相同
					his.splice(i, 1) //删除
				} else {
					// console.log("不等于");
				}
				//循环长度超过30删除
				if (his.length >= 30) { //
					his.splice(his.length - 1, 1)

				}
			} //
			//循环完成

			wx.setStorageSync("his", his); //赋值替换全部

			let arrH = wx.getStorageSync("his") || [];
			arrH.unshift(His);
			wx.setStorageSync("his", arrH); //加入新的历史记录
			console.log("处理历史记录完成的数组");
			console.log(his)


		}
		//////////////////////////////
	},
	/* 
	 视频播放到最后
	 */
	setEnd(e) {
		console.log("视频结束了")
	},
	end(e, ee) {

	},
	/* 
	视频头部提示添加到我的小程序 
	 */
	tisVideo() {
		//首次提示
		let tis = Array();
		tis = wx.getStorageSync("tisVideo");
		if (tis.length != 0) {
			this.setData({
				hisShow: false
			})
		}
	},
	//按钮
	tisx() {
		wx.setStorageSync("tisVideo", "tisx");
		this.setData({
			hisShow: false
		});
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

		// this.videoCtx = wx.createVideoContext('myVideo');
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function(e) {
		////视频下方文字
		this.setData({
			msgList: [{
					title: "请勿相信视频中上方的广告，谨防上当受骗！"
				},
				{
					title: "视频卡顿请尝试切换播放线路或联系客服！"
				},{
				title: "请必务关注微信公众号：爱宅域，以防失联！"
				}
			]
		})
		//////
	},
	save(){
		var urrl=[];
		urrl="https://ys.aizhaiyu.com/img/QR/aizhaiyu.jpg";
		    wx.previewImage({
		      current: urrl, // 当前显示图片的http链接
		      urls: [urrl] // =============重点重点=============
		    })
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	// 弹窗广告
	ad() {
		//插屏广告
		if (wx.createInterstitialAd) {
			this.interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-a530202b7793e07a'
			})
			this.interstitialAd.onLoad(() => {
				console.log('onLoad event emit')
			})
			this.interstitialAd.onError((err) => {
				console.log('onError event emit', err)
			})
			this.interstitialAd.onClose((res) => {
				console.log('onClose event emit', res)
			})
		}
		//激励广告
		if (wx.createRewardedVideoAd) {
			this.videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-9a0a313d6f544e34'
			})
			this.videoAd.onLoad(() => {
				console.log("激励开始")
			})
			this.videoAd.onError((err) => {
				console.log("激励错误")
			})
			this.videoAd.onClose((res) => {
				console.log("激励关闭")
			})
		}
	},
	// ////////////////////////////
	//点击我显示底部弹出框
	quan: function() {
		this.showModal();
	},


	//显示对话框
	showModal: function() {
		// 显示遮罩层
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: "linear",
			delay: 0
		})
		this.animation = animation
		animation.translateY(300).step()
		this.setData({
			animationData: animation.export(),
			showModalStatus: true
		})
		setTimeout(function() {
			animation.translateY(0).step()
			this.setData({
				animationData: animation.export()
			})
		}.bind(this), 200)
	},
	//隐藏对话框
	hideModal: function() {
		// 隐藏遮罩层
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: "linear",
			delay: 0
		})
		this.animation = animation
		animation.translateY(300).step()
		this.setData({
			animationData: animation.export(),
		})
		setTimeout(function() {
			animation.translateY(0).step()
			this.setData({
				animationData: animation.export(),
				showModalStatus: false
			})
		}.bind(this), 200)
	},

	///////////////////////////////

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function(e) {
		console.log(e)
		var that = this;
		return {
			title: "在线免费观看《" + this.data.title + "》",
			desc: '能白嫖绝不充钱，难道不是吗',
			imageUrl: that.data.img
		}
	},
	//朋友圈
	onShareTimeline: function(e) {
		var that = this;
		console.log(e)
		return {
			title: "在线免费观看《" + this.data.title + "》",
			imageUrl: that.data.img
		}
	},

})
